package lion.dev.image;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.lang.StringUtils;

import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiException;

public class FileFormatWriter {

	protected String name;
	protected String[] mimeTypes;
	protected String[] fileExtensions;

	public FileFormatWriter(String name, String mimeType, String fileExtension) {

		this(name, new String[] { mimeType }, new String[] { fileExtension });
	}

	public FileFormatWriter(String name, String[] mimeTypes, String[] fileExtensions) {

		this.name = name;
		this.mimeTypes = mimeTypes;
		this.fileExtensions = fileExtensions;
	}

	public String getName() {

		return this.name;
	}

	public String[] getMimeTypes() {

		return this.mimeTypes;
	}

	public String[] getFileExtensions() {

		return this.fileExtensions;
	}

	public boolean canRead(String extension) {

		if (this.fileExtensions != null) {
			for (String ext : this.fileExtensions) {
				if (StringUtils.endsWithIgnoreCase(ext, extension)) { return true; }
			}
		}
		return false;
	}

	public void writeImage(OutputStream out, BufferedImage image) throws IOException {

		try {
			Jimi.putImage(this.mimeTypes[0], image, out);
		} catch (JimiException e) {
			throw new IOException(e + ": " + e.getMessage());
		}
	}

	public String getSaveFilename(String name) {

		int index = name.lastIndexOf('.');
		if (index != -1) {
			name = name.substring(0, index);
		}
		if (this.fileExtensions != null) {
			name = name + this.fileExtensions[0];
		}
		return name;
	}

	@Override
	public String toString() {

		return this.name;
	}
}
